package com.longrise.android.byjk.advertisement.utils;

import android.os.Handler;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by callxkj on 2016/12/19.
 * 访问网络 获取图片,视频等下载类
 */

public class ADHttpUtil {

    public static final int INTERSTITIAL_DIALOG = 1;
    private int mType;
    private String mUrl;
    private ADHttpUtilCallback mCallback;
    String mFileName;
    Handler handler = new Handler();

    public void getFilePath(int type, String url, ADHttpUtilCallback callback) {
        this.mType = type;
        this.mUrl = url;
        this.mCallback = callback;
        getFilePathFromLocal();
    }

    private void getFilePathFromLocal() {
        try {
            mFileName = MD5Utils.getVal_UTF8(mUrl);
            String interstitialFolderPath = ADFileUtil.getInterstitialFolderPath();
            File file = new File(interstitialFolderPath, mFileName);
            if (file.exists()) {
                mCallback.onSuccess(file.getAbsolutePath());
            } else {
                getFilePathFromNet();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getFilePathFromNet() {
        new Thread() {
            URL url;
            private HttpURLConnection urlConn;

            @Override
            public void run() {
                try {
                    url = new URL(mUrl);
                    urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setConnectTimeout(5000);
                    urlConn.setReadTimeout(10000);
                    urlConn.connect();
                    BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
                    File file = new File(ADFileUtil.getInterstitialFolderPath(), mFileName + ".ad");
                    if (file.exists()) {
                        file.delete();
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] buf = new byte[1024];
                    int size = 0;
                    while ((size = bis.read(buf)) != -1) {
                        fos.write(buf, 0, size);
                    }
                    fos.close();
                    bis.close();
                    urlConn.disconnect();

                    File newFile = new File(ADFileUtil.getInterstitialFolderPath(), mFileName);
                    boolean b = file.renameTo(newFile);
                    if (b) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                getFilePathFromLocal();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
